#include "Net/Select.h"
#include "Base/Log/LogDefine.h"

CSelect::CSelect(void)
{
	mTV.tv_sec = 0;
	mTV.tv_usec = 0;
}

CSelect::~CSelect(void)
{
}

int CSelect::add(int socketFD)
{
	if (socketFD < 0)
	{
		LOGW("add socketFD:%d < 0 in add()", socketFD);
		return -1;
	}

	mSocketSet.insert(socketFD);

	return 0;
}

int CSelect::del(int socketFD)
{
	SELECT_SOCKET_SET::iterator it = mSocketSet.find(socketFD);
	if (it != mSocketSet.end())
	{
		mSocketSet.erase(it);
	}

	return 0;
}

int CSelect::loop(int sockNum)
{
	int ret;
#ifdef __WIN_PLATFORM__
	ret = select(sockNum, &mReadSet, nullptr, &mExceptSet, &mTV);

#elif __LINUX_PLATFORM__
	ret = select(sockNum, &mReadSet, nullptr, &mExceptSet, &mTV);
#endif // __WIN_PLATFORM__
	
	return ret;
}

int CSelect::zero()
{
	FD_ZERO(&mReadSet);
	//FD_ZERO(&mWriteSet);
	FD_ZERO(&mExceptSet);

	for (int socketFD : mSocketSet)
	{
		FD_SET(socketFD, &mReadSet);
		//FD_SET(socketFD, &mWriteSet);
		FD_SET(socketFD, &mExceptSet);
	}

	return 0;
}

bool CSelect::isReadable(int socketFD)
{
	return FD_ISSET(socketFD, &mReadSet);
}

bool CSelect::isWriteable(int socketFD)
{
	return FD_ISSET(socketFD, &mWriteSet);
}

bool CSelect::isExcept(int socketFD)
{
	return FD_ISSET(socketFD, &mExceptSet);
}

void CSelect::setTimeOut(int second, int milliscond)
{
	mTV.tv_sec = second;
	mTV.tv_usec = milliscond * 1000;
}
